import { useState, useEffect } from 'react'
import { NavLink } from 'react-router-dom'
import {
  Card,
  Breadcrumb,
  Form,
  Input,
  Button,
  Space,
  Table,
  Image,
  Switch,
  Pagination,
  Select,
  Drawer,
  message,
  Carousel
} from 'antd'
import type { Goods } from '@/types/goods'
import { getGoodsList, getCategories, updateFlag } from '@/api/goods'
import type { ColumnsType } from 'antd/es/table'
import { useFormatPrice } from '@/hook'
const { Option } = Select

export default function Goods () {
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [categories, setCategories] = useState<string[]>([])
  const [goodsList, setGoodsList] = useState([] as Goods[])
  const [total, setTotal] = useState(0)
  const [form] = Form.useForm()
  const [formatPrice] = useFormatPrice()

  // 获取商品分类
  const getCategoriesData = async () => {
    const res = await getCategories()
    setCategories(res.data)
  }

  // 获取商品列表
  const getGoodsListData = async () => {
    const results = await form.getFieldsValue(['proname', 'category', 'brand'])
    results.page = page
    results.pageSize = pageSize
    const res = await getGoodsList(results)

    setGoodsList(res.data.items)
    setTotal(res.data.total)
  }

  useEffect(() => {
    getCategoriesData()
    getGoodsListData()
  }, [page, pageSize])

  const changeState = async (
    type: 'issale' | 'isseckill' | 'isrecommend',
    proid: string,
    state: 0 | 1
  ) => {
    await updateFlag({ proid, type, state })
    if (type === 'issale') {
      message.success('更改是否售卖状态成功')
    } else if (type === 'isseckill') {
      message.success('更改是否秒杀状态成功')
    } else if (type === 'isrecommend') {
      message.success('更改是否推荐状态成功')
    }
  }

  // 查看商品详情
  const [open, setOpen] = useState(false)
  const [goods, setGoods] = useState({} as Goods)
  const showDetail = (goods: Goods) => {
    setGoods(goods)
    setOpen(true)
  }

  const columns: ColumnsType<Goods> = [
    {
      title: '轮播图图片',
      dataIndex: 'img1',
      render: img1 => {
        return <Image src={img1} style={{ width: 50, height: 50 }} />
      }
    },
    {
      title: '名称',
      dataIndex: 'proname'
    },
    {
      title: '品牌',
      dataIndex: 'brand'
    },
    {
      title: '分类',
      dataIndex: 'category',
      width: 100,
      filters: [
        { text: '家电', value: '家电' },
        { text: '口红', value: '口红' },
        { text: '键盘', value: '键盘' }
      ],
      onFilter: (value: any, record) => record.category.includes(value)
    },
    {
      title: '原价',
      dataIndex: 'originprice'
    },
    {
      title: '折扣',
      dataIndex: 'discount',
      width: 80
    },
    {
      title: '销量',
      dataIndex: 'sales'
    },
    {
      title: '是否售卖',
      dataIndex: 'issale',
      render: (_, record) => {
        return (
          <Switch
            defaultChecked={record.issale === 1}
            onChange={checked =>
              changeState('issale', record.proid, checked ? 1 : 0)
            }
          />
        )
      }
    },
    {
      title: '是否秒杀',
      dataIndex: 'isseckill',
      render: (_, record) => {
        return (
          <Switch
            defaultChecked={record.isseckill === 1}
            onChange={checked =>
              changeState('isseckill', record.proid, checked ? 1 : 0)
            }
          />
        )
      }
    },
    {
      title: '是否推荐',
      render: (_, record) => {
        return (
          <Switch
            defaultChecked={record.isrecommend === 1}
            onChange={checked =>
              changeState('isrecommend', record.proid, checked ? 1 : 0)
            }
          />
        )
      }
    },
    {
      title: '状态',
      render: (_, record) => (
        <>
          <Space>
            <Button type='primary' onClick={() => showDetail(record)}>
              查看详情
            </Button>
          </Space>
        </>
      )
    }
  ]

  return (
    <div>
      <Card>
        <Breadcrumb
          items={[
            {
              title: <NavLink to='/'>首页</NavLink>
            },
            {
              title: '商品管理'
            },
            {
              title: '商品列表'
            }
          ]}
        />
        <Form
          form={form}
          layout='inline'
          size='large'
          style={{ marginTop: 20 }}
        >
          <Form.Item label='商品名称' name='proname'>
            <Input placeholder='请输入商品名称' style={{ width: 200 }} />
          </Form.Item>
          <Form.Item label='商品分类' name='category'>
            <Select style={{ width: 200 }}>
              {categories &&
                categories.map(item => {
                  return (
                    <Option key={item} value={item}>
                      {item}
                    </Option>
                  )
                })}
            </Select>
          </Form.Item>
          <Form.Item label='品牌' name='brand'>
            <Input placeholder='请输入品牌' style={{ width: 200 }} />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type='default'>清空</Button>
              <Button type='primary' onClick={getGoodsListData}>
                搜索
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
      <Card style={{ marginTop: 10 }}>
        <Table
          dataSource={goodsList}
          columns={columns}
          pagination={false}
          rowKey='proid'
        />

        <Pagination
          style={{ marginTop: 20, textAlign: 'center' }}
          current={page}
          pageSize={pageSize}
          total={total}
          showSizeChanger
          showQuickJumper
          pageSizeOptions={[10, 20, 50, 100]}
          showTotal={total => `共 ${total} 条`}
          onChange={(page, pageSize) => {
            setPage(page)
            setPageSize(pageSize)
          }}
        />
      </Card>
      <Drawer
        title='商品详情'
        placement='right'
        onClose={() => setOpen(false)}
        open={open}
        width={'80%'}
      >
        {/* 轮播图 */}
        <Carousel autoplay>
          {goods.banners &&
            goods.banners[0].split(',').map(item => {
              return (
                <div key={item} style={{ width: 600 }}>
                  <img src={item} />
                </div>
              )
            })}
        </Carousel>
        <h3>{goods.proname}</h3>
        <h4>品牌：{goods.brand}</h4>
        <h4>分类：{goods.category}</h4>
        <h4>
          价格：
          {/* <span style={{ color: 'red' }}>
            ￥{formatPrice(goods.originprice || 0)}
          </span> */}
          <span style={{ color: 'red' }}>
            ￥{goods.originprice && formatPrice(goods.originprice)}
          </span>
        </h4>
        <h4>销量：{goods.sales}</h4>
        <h4>是否售卖：{goods.issale === 1 ? '是' : '否'}</h4>
        <h4>是否秒杀：{goods.isseckill === 1 ? '是' : '否'}</h4>
        <h4>是否推荐：{goods.isrecommend === 1 ? '是' : '否'}</h4>
        <h4>{goods.desc}</h4>
        <h4>图文详情：</h4>
        <div style={{ textAlign: 'center' }}>
          <Image src={goods.img1} />
        </div>
        <div style={{ textAlign: 'center' }}>
          <Image src={goods.img2} />
        </div>
        <div style={{ textAlign: 'center' }}>
          <Image src={goods.img3} />
        </div>
        <div style={{ textAlign: 'center' }}>
          <Image src={goods.img4} />
        </div>
      </Drawer>
    </div>
  )
}
